﻿using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;

public class SchInfoContext : DbContext
{
    public DbSet<School> schools { get; set; }
    public DbSet<Class> classes { get; set; }
    public DbSet<Student> students { get; set; }
    public DbSet<LogItem> logs { get; set; }
    public string DbPath { get; }
    public SchInfoContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = System.IO.Path.Join(path, "SchInfo.db");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}
public class School
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Class> Classes { get; set; }
}

public class Class
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int SchoolId { get; set; }
    public List<Student> Students { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ClassId { get; set; }
}

public class LogItem
{
    public int Id { get; set; }
    public string Action { get; set; }
    public int ItemId { get; set; }
}

public class Program
{
    
    static void Main(string[] args)
    {
        using var db = new SchInfoContext();

        Console.WriteLine($"Database path: {db.DbPath}.");

        // Create stu464
        Console.WriteLine("Inserting a new student-464");
        Student s1 = new Student { Id = 464, Name = "LJH" };
        db.Add(s1);
        db.SaveChanges();

        //Add to logs
        db.logs.Add(new LogItem { Action = "Add Student", ItemId = s1.Id });
        db.SaveChanges();

        // Read
        Console.WriteLine("Querying for students");
        var stu = db.students
            .OrderBy(b => b.Id)
            .First();

        // Update
        Console.WriteLine("Updating the student and adding a class");
        stu.Id = 465;
        db.SaveChanges();

        //Add to logs
        db.logs.Add(new LogItem { Action = "Update Student", ItemId = stu.Id });
        db.SaveChanges();

        //Add a class
        // Create new class and add student-464 to it
        Console.WriteLine("Inserting a new class with student-465");
        var newClass = new Class { Name = "Class-101", SchoolId = 1 };
        newClass.Students = new List<Student> { s1 };
        db.Add(newClass);
        db.SaveChanges();

        //Add to logs
        db.logs.Add(new LogItem { Action = "Add Class", ItemId = 101 });
        db.SaveChanges();


        // Delete
        Console.WriteLine("Delete the db");
        db.Remove(stu);
        db.SaveChanges();

        //Add to logs
        db.logs.Add(new LogItem { Action = "Delete db", ItemId = 0 });
        db.SaveChanges();
    }


}
